package com.xiaoming.controller;

import com.alibaba.fastjson.JSONObject;
import com.xiaoming.base.TextMessage;
import com.xiaoming.utils.CheckUtil;
import com.xiaoming.utils.HttpClientUtil;
import com.xiaoming.utils.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author xiaoming
 * @Date 2020/3/19
 */
@Slf4j
@RestController
public class DispatCherServlet {

    /**
     * 青云客智能聊天机器人API
     */
    private static final String REQEST_HTTP = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=";

    /**
     * 在微信公众号接口配置信息中配置url的时候调用该接口
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/dispatCherServlet")
    public String dispatCherServletGet(String signature, String timestamp, String nonce, String echostr) {
        // 1.验证是否微信来源
        boolean checkSignature = CheckUtil.checkSignature(signature, timestamp, nonce);
        // 2.如果是微信来源 返回 随机数echostr
        if (!checkSignature) {
            return null;
        }
        return echostr;
    }

    @PostMapping("/dispatCherServlet")
    public void dispatCherServletPost(HttpServletRequest reqest, HttpServletResponse response) throws Exception {
        reqest.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        Map<String, String> map = XmlUtils.parseXml(reqest);
        if (map == null) {
            return;
        }
        String msgType = map.get("MsgType");
        PrintWriter writer = response.getWriter();
        switch (msgType) {
            case "text":
                // 获取消息内容
                String content = map.get("Content");
                log.info("####content###:" + content);
                // 发送消息
                String toUserName = map.get("ToUserName");
                // 来自消息
                String fromUserName = map.get("FromUserName");

                // 調用智能机器人接口
                String requestResultJson = HttpClientUtil.doGet(REQEST_HTTP + content);
                JSONObject jsonObject = JSONObject.parseObject(requestResultJson);
                String result = jsonObject.getString("result");
                String msg = null;
                if (result.equals("0")) {
                    msg = jsonObject.getString("content");
                } else {
                    msg = "我不知道回答什么！";
                }
                String resultTestMsg = setTextMess(msg, toUserName, fromUserName);
                writer.print(resultTestMsg);
                break;
            default:
                break;
        }
    }

    public String setTextMess(String content, String fromUserName, String toUserName) {
        TextMessage textMessage = new TextMessage();
        textMessage.setFromUserName(fromUserName);
        textMessage.setToUserName(toUserName);
        textMessage.setContent(content);
        textMessage.setMsgType("text");
        textMessage.setCreateTime(System.currentTimeMillis());
        String messageToXml = XmlUtils.messageToXml(textMessage);
        log.info("####setTextMess()###messageToXml:" + messageToXml);
        return messageToXml;
    }

}
